package org.llc.bpmn.service;

import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.llc.bpmn.model.entity.BpmInstanceEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Service
public class BpmInstanceService {

    @Autowired
    RuntimeService runtimeService;

    @Autowired
    IdentityService identityService;

    @Autowired
    TaskService taskService;

    /**
     * 启动流程实例
     *
     * @param key       模板Key
     * @param content   审批内容
     * @param variables 流程变量
     */
    public void createBpmInstance(String key, String content, Map<String, Object> variables) {

        //当前登录人
        String userId = "admin";
        key = "process";

        String businessKey = UUID.randomUUID().toString();
        //流程发起人
        identityService.setAuthenticatedUserId(userId);
        ProcessInstance instance = runtimeService.startProcessInstanceByKey(key, businessKey);


        BpmInstanceEntity entity = new BpmInstanceEntity();
        entity.setId(businessKey);
        entity.setInstanceId(instance.getId());
        entity.setCreateTime(new Date());
        entity.setCreateUser(userId);
        entity.setContent(content);
        log.info("完成一个实例启动, {}", instance.getId());


    }




    /**
     * 完成任务审批
     *
     * @param taskId
     * @param variables
     */
    public void completeTask(String taskId, Map<String, Object> variables) {
        String userId = "admin";
        taskService.claim(taskId, userId);
        taskService.complete(taskId, variables);
        log.info("完成任务审批, {}", taskId);
    }


    /**
     * 获取待办列表
     */
    public void notifyList(){
        String userId = "xiaomi";
        List<Task> result = taskService.createTaskQuery().taskCandidateUser(userId).list();
        System.out.println(result.size());
    }




}
